﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.Samples.WindowsPhoneCloud.StorageClient.Serializers
Imports Microsoft.Samples.WindowsPhoneCloud.StorageClient.Credentials
Imports System.Net.Browser
Imports System.Net
Imports System.Globalization

Public Class CloudQueueClient
    Implements ICloudQueueClient
    Private queueBaseUri As Uri

    ''' <summary>
    ''' Initializes a new instance of the CloudQueueClient class to perform operations with Queues using the Azure Storage credentials.
    ''' </summary>
    ''' <param name="queueBaseAddress">The Queue service endpoint to use to create the client.</param>
    ''' <param name="credentials">The account credentials.</param>
    Public Sub New(ByVal queueBaseAddress As String, ByVal credentials As IStorageCredentials)
        Me.queueBaseUri = New Uri(queueBaseAddress, UriKind.Absolute)
        Me.StorageCredentials = credentials
    End Sub

    Public Property StorageCredentials() As IStorageCredentials

    Public Function GetQueueReference(ByVal queueName As String) As ICloudQueue Implements ICloudQueueClient.GetQueueReference
        Dim queueUri = New Uri(String.Format(CultureInfo.InvariantCulture, "{0}/{1}", Me.queueBaseUri.ToString().TrimEnd("/"c), queueName))
        Return New CloudQueue With {.Name = queueName, .Uri = queueUri, .StorageCredentials = Me.StorageCredentials}
    End Function

    Public Sub ListQueues(ByVal callback As Action(Of CloudOperationResponse(Of IEnumerable(Of ICloudQueue)))) Implements ICloudQueueClient.ListQueues
        Me.ListQueues(String.Empty, callback)
    End Sub

    Public Sub ListQueues(ByVal queuePrefix As String, ByVal callback As Action(Of CloudOperationResponse(Of IEnumerable(Of ICloudQueue)))) Implements ICloudQueueClient.ListQueues
        Dim serviceOperation = String.Concat(Me.queueBaseUri, "?comp=list")

        If Not String.IsNullOrEmpty(queuePrefix) Then
            serviceOperation = String.Concat(serviceOperation, "&prefix=", queuePrefix.Replace("\", "/"))
        End If

        ' Adding an incremental seed to avoid a cached response.
        serviceOperation = String.Concat(serviceOperation, "&incrementalSeed=", Date.UtcNow.Ticks)

        Dim request = CType(WebRequestCreator.ClientHttp.Create(New Uri(serviceOperation)), HttpWebRequest)
        request.Headers("x-ms-version") = "2009-09-19"
        request.Method = "GET"

        Me.StorageCredentials.SignRequest(request, -1)
        request.BeginGetResponse(
            Sub(ar)
                Try
                    If request.HaveResponse Then
                        Dim response = CType(request.EndGetResponse(ar), HttpWebResponse)
                        Dim serializer = New QueueDataContractSerializer(Me.StorageCredentials)
                        Dim results = serializer.ReadObject(response.GetResponseStream())
                        callback(New CloudOperationResponse(Of IEnumerable(Of ICloudQueue))(If(results IsNot Nothing, results.ToArray(), New CloudQueue() {}), Nothing))
                    End If
                Catch exception As Exception
                    callback(New CloudOperationResponse(Of IEnumerable(Of ICloudQueue))(Nothing, If(StorageClientExceptionParser.ParseXmlWebException(TryCast(exception, WebException)), exception)))
                End Try
            End Sub,
            Nothing)
    End Sub
End Class